package com.husk.leetcode.dp;

/**
 * <p>
 *
 * </p>
 *
 * @author hushunke@sm.vvip-u.com
 * @since 2021/4/2
 */
public class Water {


    /**
     * 面试题 17.21. 直方图的水量
     * <p>
     * https://leetcode-cn.com/problems/volume-of-histogram-lcci/
     * https://leetcode-cn.com/problems/trapping-rain-water/
     * <p>
     * leftMax[i] = max(leftMax[i−1], height[i]), 1<=i<=n−1
     * rightMax[i] = max(rightMax[i+1], height[i])，0<=i<=n-2
     * leftMax[0] = hegith[0]
     * rightMax[n-1] = height[n-1]
     * i = min(leftMax[i], rightMax[i]) - height[i]
     * ans = sum(i), 0<=i<n
     */
    public int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int n = height.length;

        int[] leftMax = new int[n];
        leftMax[0] = height[0];
        for (int i = 1; i <= n - 1; i++) {
            leftMax[i] = Math.max(leftMax[i - 1], height[i]);
        }

        int[] rightMax = new int[n];
        rightMax[n - 1] = height[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            rightMax[i] = Math.max(rightMax[i + 1], height[i]);
        }

        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans += Math.min(leftMax[i], rightMax[i]) - height[i];
        }
        return ans;
    }

}
